package cn.ztuo.bitrade.controller.contract;

import cn.ztuo.bitrade.annotation.AccessLog;
import cn.ztuo.bitrade.constant.AdminModule;
import cn.ztuo.bitrade.constant.PageModel;
import cn.ztuo.bitrade.constant.SysConstant;
import cn.ztuo.bitrade.controller.common.BaseAdminController;
import cn.ztuo.bitrade.entity.Admin;
import cn.ztuo.bitrade.entity.ContractBond;
import cn.ztuo.bitrade.entity.ContractCoin;
import cn.ztuo.bitrade.model.update.ContractCoinUpdate;
import cn.ztuo.bitrade.service.ContractBondService;
import cn.ztuo.bitrade.service.ContractCoinService;
import cn.ztuo.bitrade.service.LocaleMessageSourceService;
import cn.ztuo.bitrade.util.BindingResultUtil;
import cn.ztuo.bitrade.util.ContractUtils;
import cn.ztuo.bitrade.util.MessageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.util.Assert.notNull;


@RestController
@RequestMapping("contract/contract-coin")
public class ContractCoinController extends BaseAdminController {
    @Autowired
    private LocaleMessageSourceService messageSource;
    @Autowired
    private ContractCoinService contractCoinService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private ContractBondService bondService;


    @RequiresPermissions("contract:contract-coin:contractadd")
    @PostMapping("contractadd")
    @AccessLog(module = AdminModule.EXCHANGE, operation = "添加合约")
    public MessageResult  ContractCoinadd(@Valid ContractCoin contractCoin) {

        ContractCoin coin = contractCoinService.findBySymbol(contractCoin.getSymbol());
        if(coin!=null){
            return MessageResult.error(messageSource.getMessage("该合约已存在!"));
        }

        contractCoin = contractCoinService.save(contractCoin);
        if (contractCoin != null && contractCoin.getEnable() == 0){
            List<ContractCoin> result = new ArrayList<>();
            result.add(contractCoin);
            //发送Kafka消息，上架行情
            kafkaTemplate.send("contract-symbol", JSONObject.toJSONString(result));
            kafkaTemplate.send("contract-contract-symbol",JSONObject.toJSONString(result));
        }
        return MessageResult.getSuccessInstance(messageSource.getMessage("SUCCESS"), contractCoin);
    }
    /**
     * 获取合约详情
     * @param id
     * @return
     */
    @RequiresPermissions("contract:contract-coin:detail")
    @PostMapping("/detail")
    @AccessLog(module = AdminModule.SYSTEM,operation = "后台合约详情")
    public MessageResult detail(@RequestParam("id") Integer id){
        ContractCoin contractCoin = contractCoinService.findOne(id);
        notNull(contractCoin,"validate contract_coin.id!");
        return success(contractCoin);
    }
    /**
     * 分页查询合约列表
     * @param pageModel
     * @return
     */
    @RequiresPermissions("contract:contract-coin:page-query")
    @PostMapping("page-query")
    @AccessLog(module = AdminModule.SYSTEM,operation = "分页查找后台合约COIN")
    public MessageResult contractSelect(PageModel pageModel){
        if(pageModel.getProperty() == null){
            List<String> list = new ArrayList<>();
            list.add("id");
            List<Sort.Direction> directions = new ArrayList<>();
            directions.add(Sort.Direction.ASC);
            pageModel.setProperty(list);
            pageModel.setDirection(directions);
        }
        Page<ContractCoin> pageResult = contractCoinService.findAll(null,pageModel.getPageable());
        System.out.println(JSON.toJSONString(pageResult.getContent()));
        return success(pageResult);
    }
    /**
     * 更新合约信息
     * @param contractCoinUpdate
     * @param admin
     * @param bindingResult
     * @return
     */
    @RequiresPermissions("contract:contract-coin:update")
    @PostMapping("update")
    @AccessLog(module = AdminModule.SYSTEM,operation = "更新后台合约COIN")
    public MessageResult contractUpage(
            @Valid ContractCoinUpdate contractCoinUpdate,
            @SessionAttribute(SysConstant.SESSION_ADMIN) Admin admin,
            BindingResult bindingResult){
        ContractCoin contractCoin = contractCoinService.findOne(contractCoinUpdate.getId());
        notNull(contractCoin,"validate coin.id!");
        BeanUtils.copyProperties(contractCoinUpdate,contractCoin);
        Assert.notNull(admin,messageSource.getMessage("DATA_EXPIRED_LOGIN_AGAIN"));
        notNull(contractCoinUpdate.getSymbol(),"validate coin.symbol!");
        MessageResult result = BindingResultUtil.validate(bindingResult);
        if(result != null)
            return result;
        contractCoinService.save(contractCoin);
        return success();
    }


    /**
     * @param status     0:暂停 1:开启
     * @param symbol     空:所有
     * @throws ParseException
     */
    @RequiresPermissions("contract:contract-coin:alter-rate")
    @RequestMapping("/startOrStop")
    public MessageResult startOrStop(int status, String symbol) throws ParseException {

        if(StringUtils.isBlank(symbol)){
            List<ContractCoin> coins = ContractUtils.findBaseSymbols();
            coins = coins.stream().map(coin->{coin.setRobotStatus(status);return coin;}).collect(Collectors.toList());
            coins = contractCoinService.save(coins);
            if(coins!=null&&coins.size()>0){
                kafkaTemplate.send("contract-robot", JSON.toJSONString(coins));
            }
        }else{
            List<ContractCoin> coins = new ArrayList<>();
            ContractCoin coin = ContractUtils.getBaseSymbol(symbol);
            if(coin!=null){
                coin.setRobotStatus(status);
                coins.add(coin);
                coins = contractCoinService.save(coins);
                kafkaTemplate.send("contract-robot", JSON.toJSONString(coins));
            }
        }
        return MessageResult.success("操作成功");
    }


    /**
     * 获取所有交易区币种的单位
     *
     * @return
     */
    @RequestMapping("all-base-symbol-units")
    public MessageResult getAllBaseSymbolUnits() {
        List<ContractCoin> coins = contractCoinService.findAllSymbol();
        List<String> list = coins.stream().map(coin->coin.getCoinSymbol()).collect(Collectors.toList());
        return success(messageSource.getMessage("SUCCESS"), list);
    }
    /**
     * 获取所有交易区币种的单位
     *
     * @return
     */
    @ApiOperation(value = "获取所有可用交易对", notes = "获取所有可用交易对")
    @RequestMapping(value = "findContractSymbol",method = RequestMethod.POST)
    public MessageResult findContractSymbol() {
        List<ContractCoin> coins = contractCoinService.findAllEnabled();
        List<String> list = coins.stream().map(coin->coin.getSymbol()).collect(Collectors.toList());
        return success(messageSource.getMessage("SUCCESS"), list);
    }

    /**
     * 获取所有交易区币种的单位
     *
     * @return
     */
    @ApiOperation(value = "获取所有交易对", notes = "获取所有交易对")
    @RequestMapping(value = "findAllContractSymbol",method = RequestMethod.POST)
    public MessageResult findAllContractSymbol() {
        List<ContractCoin> coins = contractCoinService.selectByAll();
        List<String> list = coins.stream().map(coin->coin.getSymbol()).collect(Collectors.toList());
        return success(messageSource.getMessage("SUCCESS"), list);
    }


    /**
     * 杠杆列表
     * @return
     */
    @PostMapping("/findBySymbol")
    public MessageResult findBySymbol(String symbol){
        Sort sort = new Sort(Sort.Direction.DESC,"multiple");
        List<ContractBond> list = bondService.findBySymbol(symbol,sort);
        return MessageResult.getSuccessInstance("",list);
    }
    /**
     * 详情
     * @return
     */
    @PostMapping("/getBond")
    public MessageResult getBond(Long id){
        ContractBond bond = bondService.findById(id);
        return MessageResult.success("",bond);
    }
    /**
     * 修改
     * @return
     */
    @PostMapping("/updateBond")
    public MessageResult updateBond(ContractBond bond){
        if(bond.getId()==null){
            return MessageResult.error("请选择要修改的数据");
        }
        ContractBond bond1 = bondService.findById(bond.getId());
        if(StringUtils.isNotBlank(bond.getMultiple())){
            bond1.setMultiple(bond.getMultiple());
        }
        if(bond.getInitialMargin()!=null){
            bond1.setInitialMargin(bond.getInitialMargin());
        }
        bond = bondService.saveAndFlush(bond1);
        return MessageResult.getSuccessInstance("",bond);
    }
}
